/**
 * Created by yaoyc on 2016/8/11.
 * Updated by jiangw on 2017/4/26.
 * Updated by yaoyc on 2017/5/22
 *nsw
 */
/*global,nsw*/
(function ($) {
	"use strict";
	$.fn.nsw = function (options) {
		var base = $('head').data('base');
		var verify;
		this.defaults = {
			getCodeBtn: '.getcode_gg', 
			codeggInput: '.code_gg', 
			refresh:'.getcode_gg',
			btnCell: '.submit', 
			mainCell: '.bd',
			row: '.row',
			timeHint: '.timenum',
			timeInterval: 30,
			isValidate: true,
			ts: null,
			reset: '.reset',
			hasId:false,
			isPreview:false,
			errorModal:false,
			lyFields:{},
			formInfo:{}
		};
		var opt = $.extend({}, this.defaults, options);
		var defaultObj = $(this);
        if(window.parent){
           opt.isPreview =  window.parent.location.href.search('state=preview')>0;
        }else if(window.parent.location.search){
             opt.isPreview =  window.location.href.search('state=preview')>0;
        }
        if(opt.isPreview){
            	defaultObj.find(opt.getCodeBtn).attr('src','');
        }
        
		//验证函数
		verify = function verify() {
			var service = {};
			service.run = function run(type, value, msg,label) {
				switch (type) {
				    case undefined:
						return service.required(value);break;
					case 'phone':
						return service.checkPhone(value);
					case 'email':
						return service.checkEmail(value);
					case 'number':
						return service.checkNumber(value);
					case 'url':
						return service.checkUrl(value);
					case '':
						return service.required(value);
				
					default:
						return service.checkReg(type, value, msg,label);
				}
			};
			service.checkPhone = function checkPhone(value) {
				var phone = /^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/;
				return {
					flog: phone.test(value),
					msg: '请填写正确的手机号码！'
				};
			};
			service.checkEmail = function checkEmail(value) {
				var email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
				return {
					flog: email.test(value),
					msg: '请填写正确的email！'
				};
			};
			service.checkReg = function checkReg(type, value, msg,label) {
				var reg = eval(type);
				return {
					flog: reg.test(value),
					msg:label+ msg
				};
			};
			service.checkNumber = function checkNumber(value){
				var numReg = /^[0-9]*$/;
				return {
					flog: numReg.test(value),
					msg: '请填写数字！'
				};
			};
			service.checkUrl = function checkUrl(value){
				var numReg = /((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@?^=%&amp;\/~\+#])?/;
				return {
					flog: numReg.test(value),
					msg: '请填写网址！'
				};
			};
			service.required = function required(value, lable) {
				if (!value.length) {
					return {
						flog: false,
						msg: lable + '不能为空！'
					};
				} else {
					return {
						flog: true
					};
				}
			};
			service.checkForm = function checkForm(obj,errorModal) {
				var msg, pattern, label, inputLength;

				msg = obj.attr('msg') ? obj.attr('msg') : '请正确输入!';
				inputLength = obj.attr('maxLength') || 200;
				pattern = obj.attr('pattern');
				label = obj.parent(opt.row).find('.row-hd').text();
				if(!label){
					label = obj.attr('title');
				}
				if (obj.attr('label')) {
					label = obj.attr('label');
				}
				if (label) {
					label = label.replace(/[\s:?|]*/ig, '');
				}
				if (obj.attr('required')) {
					var requiredReturn = Verify.required(obj.val(), label);
					if (!requiredReturn.flog) {
						if(errorModal){
							Verify.showModal(requiredReturn.msg,false);
						}else {
							obj.siblings('.nsw-formtipbd').show().html(requiredReturn.msg);
						}
						obj.addClass('err');
						return false;
					}
				}
				if (obj.val() !== '') {
					var returnInfo = Verify.run(pattern, obj.val(), msg,label);
					if (!returnInfo.flog) {
						if(errorModal){
							Verify.showModal(returnInfo.msg,false);
						}else{
							obj.siblings('.nsw-formtipbd').show().html(returnInfo.msg);
						}
						obj.addClass('err');
						return false;
					} else {
						var totalCount =0;
						for(var i=0; i<obj.val().length; i++){
							var c = obj.val().charCodeAt(i);
							if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)){
								totalCount++;
							}
							else{
								totalCount+=2;
							}
						}
						if (totalCount > inputLength) {
							if(errorModal){
								Verify.showModal("字段长度不能超过"+inputLength/2+"个汉字或" + inputLength+"个字符",false);
							}else {
								obj.siblings('.nsw-formtipbd').show().html("字段长度不能超过"+inputLength/2+"个汉字或" + inputLength+"个字符");
							}
							obj.addClass('err');
							return false;
						} else {
							obj.removeClass('err');
							obj.siblings('.nsw-formtipbd').hide();
							return true;
						}
					}
				}
				return true;
			};
			service.checkSelect = function checkSelect(obj) {
				var label = obj.parent(opt.row).find('.row-hd').html();
				if (obj.attr('label')) {
					label = obj.attr('label');
				}
				if (label) {
					label = label.replace(/[\s:?|]*/ig, '');
				}
				if (obj.attr('required') && obj.val() === '-1') {
					obj.siblings('.nsw-formtipbd').show().html(label + "需要选择!");
					obj.addClass('err');
					return false;
				} else {
					obj.removeClass('err');
					obj.siblings('.nsw-formtipbd').hide();
				}
				return true;
			};
			service.checkAll = function checkAll(inputAndTextarea, selects) {
				var flog = true;
				inputAndTextarea.each(function () {
					var obj = $(this);
					flog = Verify.checkForm(obj,opt.errorModal) && flog;
					return flog;
				});
				selects.each(function () {
					var obj = $(this);
					flog = Verify.checkSelect(obj,opt.errorModal) && flog;
					return flog;
				});
				return flog;
			};
			service.countdown = function countdown(time) {
			
				if (time > 0) {
					time--;
					if(defaultObj.find(opt.timeHint).length){
					    defaultObj.find(opt.timeHint).html("请" + time + "秒后再次提交！");
					}else{
						if (!defaultObj.find(opt.btnCell).siblings('b').length) {
        					opt.ts = defaultObj.find(opt.btnCell).parent().append(" <b></b>");
        				}
					    opt.ts.find("b").show().html("请" + time + "秒后再次提交！");}
					
					defaultObj.find(opt.btnCell).attr("disabled", "disabled");
					setTimeout(function () {
						service.countdown(time);
					}, 1000);

				} else {
					//ts.find("b").html("");
					defaultObj.find(opt.btnCell).removeAttr("disabled");
					if(defaultObj.find(opt.timeHint).length){
					    defaultObj.find(opt.timeHint).html("");
					}else{
					   	opt.ts.find("b").hide();
					}
				}
			};
			service.getRowInfoById = function getRowInfoById(data, id) {
				if (data[id]) {
					return data[id];
				}
			};
			service.showModal = function showModal(msg,flog){
				var $tipHtml = $('<div class="nsw-modal"><div class="modal-dialog"><div class="modal-head"><span class="css-icon modal-logo"></span>消息提示 <span class="css-icon close"></span></div><div class="modal-body"><div class="modal-body-right"><p class="msg-title">感谢您的留言：</p><p class="msg">我们有您的支持将做的更好。</p><a href="javascript:void(0);" class="close-btn">关闭</a></div><div class="modal-body-left"><div class="icon css-icon"></div></div></div><div class="modal-foot"></div></div></div>');
				$tipHtml.find('.msg').html(msg);
				if(flog){
					$tipHtml.find('.modal-body-left .icon').addClass('success-message');
				}else{
					$tipHtml.find('.modal-body-left .icon').addClass('warming-message');
					$tipHtml.find('.modal-body-right .msg-title').html('错误信息:');
				}
				$("body").append($tipHtml);
				$tipHtml.find('.close,.close-btn').click(function(){
					$tipHtml.remove();
				});
			};
			return service;
		};
		var Verify = new verify();

		if(opt.hasId&&opt.lyFields){
			defaultObj.find(opt.row).each(function(){
				var ele = Verify.getRowInfoById(opt.lyFields,$(this).attr('id'));
				if(ele){
					$(this).find('input,select,textarea').attr({
						name:ele.fieldName,
						required:ele.isRequired,
						pattern:ele.regular,
						maxLength:ele.length||200,
						label:ele.title
					});
				}

			});

		}
		/*事件绑定
		 * a.验证码刷新
		 * */
		//刷新验证码(先保留默认路径,看后期是否会进行优化)
		defaultObj.find(opt.refresh).unbind('click').click(function () {
		    if(opt.isPreview){
		        return;
		    }
			defaultObj.find('.getcode_gg').attr("src", base+'Tools/code/code_gg.php?' + Math.random());
		});
		//监控input[text]  和select失去焦点后触发验证
		opt.inputAndTextarea = defaultObj.find(opt.row + " input[type='text']," + opt.row + "  textarea");
		opt.inputAndTextarea.unbind('blur').blur(function () {
			var obj = $(this);
			if(!$(this).val()){
				obj.removeClass('err');
				return
			}
			Verify.checkForm(obj,opt.errorModal);
		});
		opt.inputAndTextarea.unbind('keyup').keyup(function(){
			if(opt.errorModal){
				return;
			}
			var obj = $(this);
			var inputLength = obj.attr('maxLength') || 200;
			var totalCount =0;
			for(var i=0; i<obj.val().length; i++){
				var c = obj.val().charCodeAt(i);
				if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)){
					totalCount++;
				}
				else{
					totalCount+=2;
				}
			}
			if (totalCount > inputLength) {
				obj.siblings('.nsw-formtipbd').show().html("字段长度不能超过"+inputLength/2+"个汉字或" + inputLength+"个字符");
				obj.addClass('err');
				return false;
			} else {
				obj.removeClass('err');
				obj.siblings('.nsw-formtipbd').hide();
				return true;
			}
		});
		//select选择后
		opt.selects = defaultObj.find(opt.row + " select");
		opt.selects.unbind('change').change(function () {
			var obj = $(this);
			Verify.checkSelect(obj);
		});
		defaultObj.find(opt.reset).unbind('click').click(function () {
			defaultObj[0].reset();
		});
		//提交表单
		defaultObj.find(opt.btnCell).unbind('click').click(function () {
			var codegg,
			    isVerify;
			isVerify = Verify.checkAll(opt.inputAndTextarea, opt.selects);
			if (!isVerify) {
			    return;
			}
			if (!opt.isValidate||opt.isValidate==='false') {
				codegg = true;
			}else if(opt.formInfo.isValidate!==undefined&&!opt.formInfo.isValidate){
				codegg = true;
			} else {
			    if(opt.isPreview){
			        codegg = true;
			    }else{
			     
			       	var code_gg = defaultObj.find(opt.codeggInput).val();
			    	codegg = false;
			     $.ajax({
					type: "post",
					url: base+"Tools/code/chk_code.php?act=gg",
					data: "code=" + code_gg,
					async: false,
					success: function (msg) {
						if (msg === '1') {
							codegg = true;
							defaultObj.find(opt.getCodeBtn).attr("src", base+'Tools/code/code_gg.php?' + Math.random());
						} else {
							Verify.showModal("验证码错误!",false);
							defaultObj.find(opt.getCodeBtn).attr("src", base+'Tools/code/code_gg.php?' + Math.random());
							codegg = false;
							return;
						}
					}
				});
			    }
			
			
			}
		
			if (codegg && isVerify) {
				var dt = defaultObj.serializeObject();
				if(opt.hasId){
					dt.projId = opt.formInfo.projId;
					dt.formId = opt.formInfo._id;
				}
				var url = "";
				if ($("input[name='vcenter']").length) {
					url = $("input[name='vcenter']").val();
				}
				if (opt.formInfo.vcenter) {
					url =opt.formInfo.vcenter;
				}
				$.ajax({
					'url': url + "?json=" + JSON.stringify(dt).replace("%","%25"),
					'type': 'post',
					'dataType': 'jsonp',
					'jsonpCallback': 'callback',
					'error': function (data) {
						Verify.showModal("提交失败!",false);
						console.log(data);
					},
					'success': function (data) {
				    	defaultObj[0].reset();
						Verify.showModal(data.msg,true);
						var baseTime = opt.timeInterval||opt.formInfo.timeInterval;
						Verify.countdown(baseTime);
					}
				});

			}

		});

	};

	$.fn.serializeObject = function () {
		var o = {};
		var a = this.serializeArray();
		$.each(a, function () {
			if (o[this.name]) {
				if (!o[this.name].push) {
					o[this.name] = [o[this.name]];
				}
				o[this.name].push(this.value || '');
			} else {
				o[this.name] = this.value || '';
			}
		});
		return o;
	};

})($);
/*调用表单*/
$(function(){
    var formEl = $('.intentionalOrderFormId');
    $.each(formEl, function(index, formItem){
        var timeinterval = $(formItem).find('.timeinterval').val();
        var isvalidate = $(formItem).find('.isvalidate').val();
        $(formItem).nsw({
            btnCell: '.form-btn-submit',
            reset: '.form-btn-reset',
            timeInterval: timeinterval,
            isValidate: isvalidate,
            row: 'ul li',
            errorModal:true
        });
    });
})